import org.molamil.acto.commands.CommandContext;
import org.molamil.acto.commands.CommandResultError;
import org.molamil.acto.commands.InvalidParserError;
import org.molamil.acto.commands.cmd.XmlResponseCmd;
import org.molamil.acto.core.Logger;
import org.molamil.commons.StringUtil;

/**
 * @author Jorge Hernandez
 */
class org.molamil.acto.commands.cmd.XmlParseCmd extends XmlResponseCmd {
	
	
	// Constants
	
	public static var ERROR_INVALID_PARSER_CLASS:String = "ERROR: The Parser class could not be loaded: \"{className}\".";	public static var ERROR_INVALID_RESULT:String = "ERROR: The result was not valid for XmlParseCmd with parser: \"{className}\".";
	
	
	// Properties
	
	private static var log:Logger = Logger.getLogger("XmlParseCmd");
	
	
	// Constructor
	
	public function XmlParseCmd(context:CommandContext) {
		super(context);
	}
	
	
	// Functions
	
	private function onStatus(response:Object):Object {
		
		var result:Object = null;
		var parser:Function;
		
		var className:String;
		
		if (context.props.cmd.parser instanceof Function) {
			parser = context.props.cmd.parser;
		} else {			className = context.props.cmd.parser;			parser = eval("" + className);
		}
		
		if (parser == null) {
			var msg:String = StringUtil.replace(ERROR_INVALID_PARSER_CLASS, "{className}", className);
			log.severe("InvalidParserError: " + msg);
			throw new InvalidParserError(msg);
		}
		
		try {
			result = parser.parse(XML(response));
		} catch (e:org.molamil.acto.core.ParserError) {
			var msg:String = StringUtil.replace(ERROR_INVALID_RESULT, "{className}", className);
			log.severe("CommandResultError: " + msg);
			throw new CommandResultError(msg, response);
		}
		
		return result;
		
	}
	
	
}
